import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Form, Input, Select, InputNumber, message, Popconfirm, Card, Image } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Search } = Input;

interface Product {
  id: number;
  name: string;
  category: string;
  price: number;
  stock: number;
  status: 'on' | 'off';
  description?: string;
  image?: string;
  createTime: string;
}

const ProductList: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = async () => {
    setLoading(true);
    try {
      // 模拟 API 调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockData: Product[] = [
        {
          id: 1,
          name: 'iPhone 15 Pro',
          category: 'electronics',
          price: 7999,
          stock: 50,
          status: 'on',
          description: '最新款苹果手机',
          image: 'https://via.placeholder.com/60x60?text=iPhone',
          createTime: '2024-01-15',
        },
        {
          id: 2,
          name: 'MacBook Pro',
          category: 'electronics',
          price: 12999,
          stock: 30,
          status: 'on',
          description: '苹果笔记本电脑',
          image: 'https://via.placeholder.com/60x60?text=Mac',
          createTime: '2024-01-14',
        },
        {
          id: 3,
          name: '咖啡杯',
          category: 'daily',
          price: 49,
          stock: 0,
          status: 'off',
          description: '陶瓷咖啡杯',
          image: 'https://via.placeholder.com/60x60?text=Cup',
          createTime: '2024-01-13',
        },
      ];
      setProducts(mockData);
    } catch (error) {
      message.error('加载商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingProduct(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    setModalVisible(true);
    form.setFieldsValue(product);
  };

  const handleDelete = async (id: number) => {
    try {
      // 模拟删除
      await new Promise(resolve => setTimeout(resolve, 500));
      setProducts(products.filter(product => product.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleStatusChange = async (id: number, status: 'on' | 'off') => {
    try {
      const updatedProducts = products.map(product =>
        product.id === id ? { ...product, status } : product
      );
      setProducts(updatedProducts);
      message.success('状态更新成功');
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingProduct) {
        // 更新商品
        const updatedProducts = products.map(product =>
          product.id === editingProduct.id
            ? { ...product, ...values }
            : product
        );
        setProducts(updatedProducts);
        message.success('更新成功');
      } else {
        // 添加商品
        const newProduct: Product = {
          id: Math.max(...products.map(p => p.id)) + 1,
          ...values,
          createTime: new Date().toISOString().split('T')[0],
        };
        setProducts([...products, newProduct]);
        message.success('添加成功');
      }
      setModalVisible(false);
    } catch (error) {
      message.error('操作失败');
    }
  };

  const filteredProducts = products.filter(product =>
    product.name.toLowerCase().includes(searchText.toLowerCase()) ||
    product.description?.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    {
      title: '商品图片',
      dataIndex: 'image',
      key: 'image',
      render: (image: string) => (
        <Image
          width={60}
          height={60}
          src={image}
          fallback="https://via.placeholder.com/60x60?text=No+Image"
          style={{ objectFit: 'cover' }}
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => (
        <Tag color="blue">
          {category === 'electronics' ? '电子产品' : 
           category === 'daily' ? '日用品' : 
           category === 'clothing' ? '服装' : category}
        </Tag>
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `¥${price.toLocaleString()}`,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      render: (stock: number) => (
        <Tag color={stock > 0 ? 'green' : 'red'}>
          {stock} 件
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'on' ? 'green' : 'red'}>
          {status === 'on' ? '上架' : '下架'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Product) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button 
            type="link" 
            onClick={() => handleStatusChange(record.id, record.status === 'on' ? 'off' : 'on')}
          >
            {record.status === 'on' ? '下架' : '上架'}
          </Button>
          <Popconfirm
            title="确定删除这个商品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              添加商品
            </Button>
          </Space>
          <Search
            placeholder="搜索商品名称或描述"
            allowClear
            style={{ width: 300 }}
            onSearch={setSearchText}
          />
        </div>

        <Table
          columns={columns}
          dataSource={filteredProducts}
          rowKey="id"
          loading={loading}
        />
      </Card>

      <Modal
        title={editingProduct ? '编辑商品' : '添加商品'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="商品名称"
            name="name"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品分类"
            name="category"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select>
              <Option value="electronics">电子产品</Option>
              <Option value="daily">日用品</Option>
              <Option value="clothing">服装</Option>
              <Option value="books">图书</Option>
              <Option value="sports">运动户外</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber
              min={0}
              precision={2}
              style={{ width: '100%' }}
              formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            />
          </Form.Item>

          <Form.Item
            label="库存数量"
            name="stock"
            rules={[{ required: true, message: '请输入库存数量' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            label="商品状态"
            name="status"
            rules={[{ required: true, message: '请选择商品状态' }]}
          >
            <Select>
              <Option value="on">上架</Option>
              <Option value="off">下架</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="商品图片"
            name="image"
          >
            <Input placeholder="请输入图片URL" />
          </Form.Item>

          <Form.Item
            label="商品描述"
            name="description"
          >
            <Input.TextArea rows={4} placeholder="请输入商品描述" />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingProduct ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductList;